package com.bcx.crm.java.pinyin;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created by ys on 2018/3/26.
 */
public class PinYinUtil {
    public static void main(String[] args) {
        System.out.println(converterToPinYin("杨申"));
    }
    public static String converterToPinYin(String chines){
        String pinyinName = "";
        char[] chars = chines.toCharArray();
        HanyuPinyinOutputFormat hanYuPinyin = new HanyuPinyinOutputFormat();

        hanYuPinyin.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        hanYuPinyin.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0;i<chars.length;i++){
            String s = String.valueOf(chars[i]);
            if (s.matches("[\\u4e00-\\u9fa5]")) {
                try {
                    String[] mPinyinArray = PinyinHelper.toHanyuPinyinStringArray(chars[i], hanYuPinyin);
                    pinyinName += mPinyinArray[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += chars[i];
            }
        }
        return pinyinName;
    }
}
